/*
 * ConfigManager.java
 *
 * Created on November 2, 2006, 2:42 PM
 */
package com.viweb.storemanager.entity;

import com.thoughtworks.xstream.XStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 *
 * @author Nguyễn Anh Minh
 * E-mail: anhminhnguyen@gmail.com
 */
public class ConfigManager {

    private final String FilePath = System.getProperty("user.dir") + "\\config.xml";

    /** Creates a new instance of ConfigManager */
    public ConfigManager() {
    }

    private void initConfig() {
        AppConfig object = new AppConfig();
        this.writeConfig(object);
    }

    public boolean writeConfig(AppConfig object) {
        boolean ret = true;

        try {
            FileOutputStream output = new FileOutputStream(FilePath);
            OutputStream bOutput = new BufferedOutputStream(output);
            OutputStreamWriter outputWriter = new OutputStreamWriter(bOutput, "UTF-8");
            outputWriter.write(new XStream().toXML(object));
            outputWriter.flush();
            outputWriter.close();
        } catch (Exception ex) {
            ret = false;
        } finally {
            return ret;
        }
    }

    public AppConfig readConfig() {
        // Khởi tạo file cấu hình nếu chưa tồn tại
        File file = new File(FilePath);
        if (!file.exists()) {
            this.initConfig();
        }

        Object object = null;

        try {
            FileInputStream input = new FileInputStream(FilePath);
            InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");
            object = new XStream().fromXML(inputReader);
        } catch (Exception ex) {
            System.out.println("Lỗi khi đọc thông tin cấu hình!");

            this.initConfig();
            this.readConfig();
        } finally {
            return (AppConfig) object;
        }
    }
}
